package com.dabaozhan.modules.wx_app.controller;

import java.util.List;

import com.aliyuncs.exceptions.ClientException;
import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.Constants;
import com.dabaozhan.common.utils.RandomUtils;
import com.dabaozhan.common.utils.Utils;
import com.dabaozhan.common.utils.aliyun.sms.SmsMessage;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.*;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.service.*;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "用户接口", description = "用户接口")
@RestController
@RequestMapping("/wx_app")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    /**用户*/
    @Autowired
    private UserService userService;

    /**短信*/
    @Autowired
    private SmsService smsService;

    /**账户*/
    @Autowired
    private AccountService accountService;

    /**支付密码*/
    @Autowired
    private PayPassService payPassService;

    /**类目添加*/
    @Autowired
    private SiteCategoryService siteCategoryService;

    /**查询所有系统类目*/
    @Autowired
    private SysCategoryService sysCategoryService;

    @ApiOperation(value = "登录")
    @RequestMapping(value = "/login")
    public String login(UserEntity v, String code,String userType) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            UserEntity user = userService.findByPhone(v.getTelephone());
            if ("1".equals(userType)) {
                SmsEntity sms = new SmsEntity();
                sms.setPhone(v.getTelephone());
                sms.setCode(code);
                sms.setStatus(4);
                List<SmsEntity> smsVo = smsService.findPhone(sms);
                if (smsVo.size() > 0) {
                    if (smsVo.get(smsVo.size() - 1).getPhone().equals(v.getTelephone())) {
                        if (code.equals(smsVo.get(smsVo.size() - 1).getCode())) {
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                            responseDto.setResult(user);
                        }else {
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_201);
                        }
                    }else {
                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_202);
                    }
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_203);
                }
            }else {
                String password = Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY);
                if (user.getPassword().equals(password)) {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                    responseDto.setResult(user);
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_208);
                }
            }
        } catch(RRException re) {
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("登录发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("登录发生异常:{}-返回结果:{}",JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "查询手机号是否注册")
    @RequestMapping(value = "/queryTelephone")
    public String queryTelephone(String telephone) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            UserEntity v = userService.findByPhone(telephone);
            if (v != null) {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_205);
            } else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_206);
            }
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("查询手机号是否存在,异常详情如下:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("查询手机号是否存在请求参数:{}-返回结果:{}",JSON.toJSONString(telephone),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "查询用户接口")
    @RequestMapping(value = "/findByUserId")
    public String findByUserId(String userId) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            UserEntity user = userService.findByUserId(userId);
            /*** 是否设置支付密码*/
            PayPassEntity payPass = payPassService.findByPayUserId(userId);
            if (payPass != null) {
                user.setPayStatus(1);
            } else {
                user.setPayStatus(2);
            }
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
            responseDto.setResult(user);
        } catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("查询用户信息,异常详情如下:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("查询用户信息请求参数:{}-返回结果:{}",JSON.toJSONString(userId),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "校验短信验证码-新增")
    @RequestMapping(value = "/toVerifyCode")
    public String toVerifyCode(UserEntity v, String code,String userType) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            SmsEntity sms = new SmsEntity();
            sms.setPhone(v.getTelephone());
            sms.setCode(code);
            sms.setStatus(3);
            List<SmsEntity> smsVo = smsService.findPhone(sms);
            if (smsVo.size()>0) {
                if (smsVo.get(smsVo.size()-1).getPhone().equals(v.getTelephone())) {
                    if (code.equals(smsVo.get(smsVo.size()-1).getCode())) {
                        if ("1".equals(userType)) {
                            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                        }else {
                            //用户类型 1 企业
                            v.setType(1);
                            //状态 1 未认证 2 认证失败 3 认证成功
                            v.setAuditStatus(1);
                            //状态 1 正常 2 禁用
                            v.setStatus(1);
                            //注册手机号
                            v.setUserName(v.getTelephone());
                            //来源 1 微信个人2 pc 3 回收员 4 司机 5分拣中心
                            v.setWxType(5);
                            //密码
                            v.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
                            /**添加用户*/
                            int flag = userService.saveUser(v);
                            if (flag != 0) {
                                /**添加账户*/
                                AccountEntity accountEntity = new AccountEntity();
                                //金额
                                accountEntity.setAmount(0f);
                                //用户id
                                accountEntity.setUserId(v.getId());
                                //账户类型 1 绿大侠 2 分拣中心
                                accountEntity.setType(2);
                                accountService.saveSiteAccount(accountEntity);

                                /**类目添加*/
                                List<SysCategoryEntity> sysCategoryList = sysCategoryService.findSysCategory();
                                if (sysCategoryList.size()>0) {
                                    for (SysCategoryEntity sysCategoryEntity : sysCategoryList) {
                                        if ("0".equals(sysCategoryEntity.getParentId())) {
                                            SiteCategoryEntity siteCategoryEntity = new SiteCategoryEntity();
                                            siteCategoryEntity.setCategoryId(RandomUtils.randomStr());
                                            siteCategoryEntity.setStatus(1);
                                            siteCategoryEntity.setUserId(v.getId());
                                            siteCategoryEntity.setName(sysCategoryEntity.getTwoName());
                                            //父id
                                            siteCategoryEntity.setParentId(sysCategoryEntity.getCategoryId());

                                            siteCategoryService.saveSiteCategoey(siteCategoryEntity);
                                        }
                                    }
                                }
                                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                                responseDto.setResult(v);
                            }
                        }
                    }else {
                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_201);
                    }
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_202);
                }
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_203);
            }
        } catch (RRException re) {
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        }catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("用户注册-短信验证码:",e);
        }finally{
            //记录请求入参和返回日志
            LOGGER.info("用户注册-短信验证码 请求参数:{}-返回结果:{}","toVerifyCode:"+v,JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "打包站用户修改")
    @RequestMapping(value = "/updateUser")
    public String updateUser(UserEntity v) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            UserEntity user = userService.findByUserId(v.getId());
            if (user != null) {
                if (v.getSiteName() != null) {
                    user.setSiteName(v.getSiteName());
                }
                if (v.getPassword() != null) {
                    v.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
                }
                if (v.getProvince() != null) {
                    user.setProvince(v.getProvince());
                }
                if (v.getCity() != null) {
                    user.setCity(v.getCity().replaceAll(" ", ""));
                }
                if (v.getArea() != null) {
                    user.setArea(v.getArea().replaceAll(" ", ""));
                }
                if (v.getAddress() != null) {
                    user.setAddress(v.getAddress());
                }
                if (v.getContacts() != null) {
                    user.setContacts(v.getContacts());
                }
                if (v.getTelephone() != null) {
                    user.setTelephone(v.getTelephone());
                    user.setUserName(v.getTelephone());
                }
                if (v.getLat() != null) {
                    user.setLat(v.getLat());
                }
                if (v.getLng() != null) {
                    user.setLng(v.getLng());
                }
                userService.updateUser(user);
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                responseDto.setResult(user);
            }
        }catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("修改用户信息发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("修改用户信息发生异常:{}-返回结果:{}",JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "修改手机号")
    @RequestMapping(value = "/updateUserPhone")
    public String updateUserPhone(UserEntity v,String code) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            SmsEntity sms = new SmsEntity();
            sms.setPhone(v.getTelephone());
            sms.setCode(code);
            sms.setStatus(1);
            List<SmsEntity> smsVo = smsService.findPhone(sms);
            if (smsVo.size() > 0) {
                if (smsVo.get(smsVo.size() - 1).getPhone().equals(v.getTelephone())) {
                    if (code.equals(smsVo.get(smsVo.size() - 1).getCode())) {
                        UserEntity user = userService.findByUserId(v.getId());
                        user.setUserName(v.getTelephone());
                        user.setTelephone(v.getTelephone());
                        userService.updateUser(user);

                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                        responseDto.setResult(user);
                    }else {
                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_201);
                    }
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_202);
                }
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_203);
            }
        }catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("修改用户信息发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("修改用户信息发生异常:{}-返回结果:{}",JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }

    @ApiOperation(value = "用户忘记密码")
    @RequestMapping(value = "/updatePassword")
    public String updatePassword(UserEntity v,String code) {
        ResponseDto<UserEntity> responseDto = new ResponseDto<UserEntity>();
        try {
            SmsEntity sms = new SmsEntity();
            sms.setPhone(v.getTelephone());
            sms.setCode(code);
            sms.setStatus(6);
            List<SmsEntity> smsVo = smsService.findPhone(sms);
            if (smsVo.size() > 0) {
                if (smsVo.get(smsVo.size() - 1).getPhone().equals(v.getTelephone())) {
                    if (code.equals(smsVo.get(smsVo.size() - 1).getCode())) {
                        UserEntity user = userService.findByPhone(v.getTelephone());
                        user.setPassword(Utils.md5(v.getPassword(), Constants.PAY_PASS_CACHE_KEY));
                        userService.updateUser(user);
                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_100);
                        responseDto.setResult(user);
                    }else {
                        responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_201);
                    }
                }else {
                    responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_202);
                }
            }else {
                responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_203);
            }
        }catch(RRException re){
            responseDto.setCode(re.getCode());
            responseDto.setMessage(re.getMessage());
        } catch (Exception e) {
            responseDto.setResponseCodeEnum(ResponseCodeEnum.ResponseCode_500);
            //记录异常日志
            LOGGER.error("用户忘记密码修改发生异常:",e);
        } finally {
            //记录请求入参和返回日志
            LOGGER.info("用户忘记密码修改发生异常:{}-返回结果:{}",JSON.toJSONString(v),JSON.toJSONString(responseDto));
        }
        return JSON.toJSONString(responseDto);
    }


}

